package cn.serenedream.sbbook;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;

import java.io.IOException;

//@Service
public class MyIsbnBookService implements BookService{
    public Book getBookByIsbn(String isbn) throws IOException {
        Book book = null;
        String url = "http://120.24.69.59:8083/book/isbn/" + isbn + "?apikey=sb.250.s.j.b";
        String user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0";
        Document document = Jsoup.connect(url).userAgent(user_agent).ignoreContentType(true).get();
        String result = document.body().text();
        ObjectMapper mapper = new ObjectMapper();
        JsonNode originBookInfo = mapper.readTree(result);
        if (originBookInfo != null && originBookInfo.has("ret") && originBookInfo.get("ret").asInt() == 0) {
            JsonNode data = originBookInfo.get("data");

            String title = data.path("name").asText(null);
            String author = data.path("author").asText(null);
            String publisher = data.path("publishing").asText(null);
            String published = data.path("published").asText(null);
            String description = data.path("description").asText(null);
            String coverImage = data.path("photoUrl").asText(null);
            String price = data.path("price") != null ? data.path("price").asText().replace("元", "") : null;
            String doubanScore = data.path("doubanScore").asText(null);
            String page = data.path("pages").asText(null);
            String authorIntro = data.path("authorIntro").asText(null);

            result = title + "||" + author + "||" + publisher + "||" + published
                    + "||" + description + "||" + coverImage + "||" + price
                    + "||" + doubanScore + "||" + page + "||" + authorIntro;
            book = new Book();
            book.setIsbn(isbn);
            book.setTitle(title);
            book.setAuthor(author);
            book.setAuthorIntro(authorIntro);
            book.setPublisher(publisher);
            book.setPublishDate(published);
            book.setDescription(description);
            book.setCoverImage(coverImage);
            book.setPrice(price);
            book.setDoubanScore(doubanScore);
            book.setPage(page);
        }
        return book;
    }
}
